package cn.claim.storage.tools;

import java.io.*;
import java.net.Socket;

/**
 * Created by claim on 17-7-7.
 */
public final class FileUploader {
    private final File source;
    private final Socket target;

    public FileUploader(File source, Socket target) {
        this.source = source;
        this.target = target;
    }

    /**
     * Transport a part of a file. The part size is {@code 1024 * bufferSize}.
     *
     * @return A int value means:
     * Greater than 0 - the file transporting is done.
     * Equals to 0 - the file transporting may not finish.
     * Less than 0 - the file transporting is interrupted.
     */
    public int upload(long offset) {
        int maxLength = 1024;
        RandomAccessFile input = null;
        OutputStream output;
        try {
            input = new RandomAccessFile(source, "r");
            output = target.getOutputStream();
            byte[] buffer = new byte[Integer.parseInt(Config.getProp("bufferSize","1024"))];
            int length;
            input.seek(offset);
            while (maxLength > 0 && (length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
                maxLength--;
            }
            if (maxLength < 1024)
                output.flush();
            return maxLength;
        } catch (IOException e) {
            try {
                System.out.println("传输失败, 稍后将进行重试");
                Thread.sleep(5000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return -1;
    }

//    public static void main(String[] args) {
//        Socket socket = null;
//        try {
//            socket = new Socket("localhost", 5555);
//            File uploaded = new File("./README.md");
//            FileUploader uploader = new FileUploader(uploaded, socket);
//            uploader.upload(4 * 1024);
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (socket != null) {
//                    socket.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//
//    }
}
